<?php
namespace Home\Controller;
use Think\Controller;
class GoodsController extends CommonController {
   
	private $userid ;
	private $num = 5;

//	public function _initialize()
//	{
//		$this->userid = session('business_id');
//		$this->assign('shop_id', $this->userid);
//	}

	/**
	 * 商品列表
	 */
	public function index() 
	{
		$goods_name 	= I('post.key_word');
		$intro 			= I('post.intro');

		switch($intro){
			case '':
			case 'is_all': 
					$where = '';
					break;
			case 'is_hot': 
					$where['is_hot'] = 1;
					break;
			case 'is_new': 
					$where['is_new'] = 1;
					break;
			case 'is_top': 
					$where['is_top'] = 1;
					break;
		}
		$this->assign('intro1', $intro);

		
		if(!empty($goods_name)){
			$where['goods_name'] = array('like', '%'.$goods_name.'%');
		}



		$goods = M('goods');
		$count = $goods->where($where)->count();
		$Page  = new \Think\Page($count,$this->num);
		$show  = $Page->show();

		$field = array('id','shop_cat_id','cat_id','goods_name','goods_thumb','goods_sn','sell_price','sort_order','goods_number','is_pass','status','is_hot','is_new','is_top','clicks','add_time');

		$list  = $goods
					->field($field)
					->where($where)
					->order('id desc')
					->limit($Page->firstRow.','.$Page->listRows)
					->select();

		// $shop_cat_ids = array_column($list, 'shop_cat_id');
		// $c = count($shop_cat_ids);
		// for($i=0; $i<$c; $i++){
		// 	if(empty($shop_cat_ids[$i]))
		// 		unset($shop_cat_ids[$i]);
		// }
		// $shop_cat_ids = array_unique($shop_cat_ids);

		// $where_shop_cate['id'] = array('in', $shop_cat_ids);
		// $shop_cat_name = M('shop_cate')->where($where_shop_cate)->field('id,cat_name')->select();

		// $shop_cat_names = array_column($shop_cat_name, 'cat_name');

		// $shop_cats = array_combine($shop_cat_ids, $shop_cat_names);

		foreach ($list as $k => $v) {
			$list[$k]['goods_thumb'] 	= C('IMGURL').'/'.$v['goods_thumb'];
			// $list[$k]['shop_cat_name'] 	= $shop_cats[$v['shop_cat_id']];
		}
		// dump($list);die;
		$this->assign('list',$list);
		$this->assign('page',$show);
		$this->display(); 
	}

	// 添加页面
	public function add()
	{
		session('business_id', 5);

		// 获取品牌信息
		$brand = D('brand')->all();
		$this->assign('brand', $brand);

		// 获取商品 的 商城分类
		$cate = R('Cate/first');
		$this->assign('cate', $cate);		

		// 获取商品 的 商家分类
		$shopCate = R('ShopCate/first', array($this->userid));
		$this->assign('shopCate', $shopCate);

		$this->display();
	}
	
	// 添加操作
	public function insert()
	{
		$goods = $_POST;

		// 检测
		$goods['goods_name']		= I('post.goods_name');

		if(empty($goods['goods_name']))
			$this->error('商品名称为必填项！');

		$goods['user_id'] 			= session('business_id');
		$goods['shop_cat_id'] 		= end($goods['shop_cate_id']);
		$goods['shop_catids'] 		= implode(',', $goods['shop_cate_id']);
		$goods['cat_id'] 			= end($goods['cate_id']);
		$goods['cat_ids'] 			= implode(',', $goods['cate_id']);
		$goods['brand_name']		= $this->get_brand_name($goods['brand_id'])['name'];

		// 这一行可以读取 session
		$goods['shop_name']			= $this->get_shop_name($goods['shop_id'])['business_name'];
		$goods['content'] 			= $goods['editorValue'];
		$goods['content'] 			= htmlspecialchars($goods['content']);

		// 调整多图的存储格式
		$goods['imglist'] 			= explode('|', $goods['imglist']);
		$goods['imglist'] 			= str_replace("\\", "", json_encode($goods['imglist']));

		// 拼接参数
		foreach ($goods['para']['name'] as $k => $v) {
			$para[$v] = $goods['para']['value'][$k];
		}
		$goods['goods_para']		= json_encode($para, JSON_UNESCAPED_UNICODE);
		$goods['add_time']			= time();
		$goods['update_time']		= time();

		$attr 						= $goods['attr'];

		unset($goods['editorValue']);
		unset($goods['shop_cate_id']);
		unset($goods['cate_id']);
		unset($goods['attr']);
		unset($goods['para']);

		$goods_id = M('goods')->add($goods);
		if($goods_id){
			// 调用方法 将商品的属性存入到数据库
			$this->addAttr($goods_id, $attr);
			$this->success('添加商品成功！', U('index'));
		}else{
			$this->error('添加商品失败！');
		}
	}

	/**
	* 修改页面
	*/
	public function edit()
	{
		session('business_id', 5);

		// 获取品牌信息
		$brand = D('brand')->all();
		$this->assign('brand', $brand);

		// 获取商品 的 商城分类
		$cate = R('Cate/first');
		$this->assign('cate', $cate);		

		// 获取商品 的 商家分类
		$shopCate = R('ShopCate/first', array($this->userid));
		$this->assign('shopCate', $shopCate);

		$goods_id = I('get.goods_id');
		
		$goods = D('goods')->getone($goods_id);

		$goods['content'] 			= html_entity_decode($goods['content']);
		$goods['goods_para'] 		= json_decode($goods['goods_para'], true);

		// 判断属性长度
		$goods['cat_ids']			= explode(',' , $goods['cat_ids']);
		$goods['shop_catids']		= explode(',', $goods['shop_catids']);
		$goods['cat_count']			= count($goods['cat_ids']);
		$goods['shop_cat_count']	= count($goods['shop_catids']);

		// 查询 属性名称
		$goods['cat_names']			= D("cate")->get_name($goods['cat_ids']);
		$goods['shop_cat_names']	= D("shop_cate")->get_name($goods['shop_catids']);

		// 调整多图的存储格式
		$goods['imglist'] 			= str_replace('[', '', $goods['imglist']);
		$goods['imglist'] 			= str_replace(']', '', $goods['imglist']);
		$goods['imglist'] 			= str_replace('","', '|', $goods['imglist']);
		$goods['imglist'] 			= trim($goods['imglist'], '"');
		

		$this->assign('goods', $goods);
		$this->display();
    }

    /**
     * 添加和修改操作
     */
    public function update()
    {
    	$goods = $_POST;

		// 检测
		$goods['goods_name']		= I('post.goods_name');

		if(empty($goods['goods_name']))
			$this->error('商品名称为必填项！');

		$goods['user_id'] 			= session('business_id');
		$goods['brand_name']		= $this->get_brand_name($goods['brand_id'])['name'];

		// 这一行可以读取 session
		$goods['shop_name']			= $this->get_shop_name($goods['shop_id'])['business_name'];
		$goods['content'] 			= $goods['editorValue'];
		$goods['content'] 			= htmlspecialchars($goods['content']);

		// 调整多图的存储格式
		$goods['imglist'] 			= explode('|', $goods['imglist']);
		$goods['imglist'] 			= str_replace("\\", "", json_encode($goods['imglist']));

		// 拼接参数
		foreach ($goods['para']['name'] as $k => $v) {
			$para[$v] = $goods['para']['value'][$k];
		}
		$goods['goods_para']		= json_encode($para, JSON_UNESCAPED_UNICODE);
		$goods['update_time']		= time();

		$attr 						= $goods['attr'];

		unset($goods['editorValue']);
		unset($goods['cate_id1']);
		unset($goods['cate_id2']);
		unset($goods['cate_id3']);
		unset($goods['shop_cate_id1']);
		unset($goods['shop_cate_id2']);
		unset($goods['shop_cate_id3']);
		unset($goods['attr']);
		unset($goods['para']);

		$goods_id 		= $goods['goods_id'];
		$where['id'] 	= $goods_id;

		unset($goods['goods_id']);

		$res = M('goods')->where($where)->save($goods);
		if($res){
			// 调用方法 将商品的属性存入到数据库
			$this->delAttr($goods_id);
			$this->addAttr($goods_id, $attr);
			$this->success('修改商品成功！', U('index'));
		}else{
			$this->error('修改商品失败！');
		}
    }

    // public function del()
    // {
    // 	$where['goods_id'] = I('get.id');
    // 	die;
    // }
    
    /**
     * 修改商品的状态
     */
    public function change_status()
    {
    	$where['id'] 	= I('post.goods_id');
    	$data['status'] = I('post.status') == 1 ? 0 : 1 ;

    	$info = M('goods')->where($where)->save($data);
    	$this->ajaxReturn($info);
    }

    /**
     * 修改商品的排序
     */
    public function change_order()
    {
    	$where['id'] 		= I('post.goods_id');
    	$data['sort_order'] = I('post.sort_order');

    	$info = M('goods')->where($where)->save($data);
    	$this->ajaxReturn($info);
    }















    /************************    以下是便利操作     **********************/

    /**
     * 添加商品属性
     */
    public function addAttr($goods_id, $attr)
    {

    	foreach ($attr as $k => $v) {
    		foreach ($v as $key => $value) {
	    		$attrValue['attr_id'] 	= $k;
	    		$attrValue['value'] 	= $value;
	    		$attrValue['add_time'] 	= time();

	    		// 向 attr_value 表中存入数据
	    		$attr_value_id = M('attr_value')->add($attrValue);
	    		
	    		// 向 attribute 表中存入数据
	    		$attribute['goods_id'] 			= $goods_id;
	    		$attribute['attr_id'] 			= $k;
	    		$attribute['attr_value_id'] 	= $attr_value_id;
	    		$attribute['add_time'] 			= time();
	    		$res = M('attribute')->add($attribute);
    		}
    	}

    	return $res;
    }

    /**
     * 删除商品属性
     */
    public function delAttr($goods_id)
    {
    	$field = 'id,goods_id,attr_id,attr_value_id';

    	$attribute = M('attribute');
    	$where['goods_id'] = $goods_id;

    	$info = $attribute->where($where)->field($field)->select();

		if($info){
	
	    	$attributes 	= array_column($info, 'id');
	    	$attr_values 	= array_column($info, 'attr_value_id');

	    	// 删除操作
	    	$where_attribute['id'] = array('in', $attributes);
	    	$res1 = M('attribute')->where($where_attribute)->delete();

	    	$where_attr_value['id'] = array('in', $attr_values);
	    	$res1 = M('attr_value')->where($where_attr_value)->delete();
		}
    }

    /**
     * ajax 获取商品的参数
     * @return [type] [description]
     */
    public function para_ajax()
    {
    	$cate_id = I('post.cate_id');
    	$info = D('attr')->getAttr($cate_id);
    	echo json_encode($info, JSON_UNESCAPED_UNICODE);
    }

    // 返回属性 （ 商品的修改 ）
    public function ajax_attr_val()
    {
    	$goods_id = I('post.goods_id');
    	$where['at.goods_id'] = $goods_id;

    	$field = array('at.attr_id,attr.attr_name,at_val.value');
    	
    	$info = M('attribute')->alias('at')
			    	->join('__ATTR__ as attr ON attr.id = at.attr_id')
			    	->join('__ATTR_VALUE__ as at_val ON at_val.id = at.attr_value_id')
			    	->where($where)->field($field)
			    	->select();

		// 添加一个标记为 ， 用于在修改页面中  区分属性的显示状态
		$flag = '';
		$attr_ids = array_column($info, 'attr_id');
		$attr_id_count = array_count_values($attr_ids);

		unset($attr_ids);

		foreach ($info as $k => $v) {
			if($flag != $v['attr_id']){
				$flag = $v['attr_id'];
				$info[$k]['flag'] = 1;
				if($attr_id_count[$v['attr_id']] == 1){
					$info[$k]['flag'] = 2;
				}
			}else{
				$info[$k]['flag'] = 0;
			}
		}

    	echo json_encode($info, JSON_UNESCAPED_UNICODE);
    }

    // 获取品牌名称
    public function get_brand_name($brand_id)
    {
    	$where['id'] = $brand_id;
    	return M('brand')->where($where)->field('name')->find();
    }

    // 获取店铺名称
    public function get_shop_name($shop_id)
    {
    	$where['id'] = $shop_id;
    	return M('business')->where($where)->field('business_name')->find();
    }

}